/**
 * Created by jiangxiaowei on 2016/12/19.
 */

'use strict';
let PublishLog = require('../dao/publish-log-model');

let PublishLogService = module.exports = {

  addPublishLog: function(log) {
    return new Promise((resolve,reject)=>{
      let entity = new PublishLog(log);
      entity.save((err,data)=>{
        err ? reject(err) : resolve(data);
      })
    })
  },

  getPublishLogs: async function({envCode,projectName,pageNum,pageSize}) {
    let _self = this;
    pageNum = parseInt(pageNum);
    pageSize = parseInt(pageSize);
    let publishLogs;   //日志list
    let totalCount = await _self.getLogsCount({envCode,projectName});  //总条数
    if (pageNum > 0) {
      let index = pageSize*pageNum;
      let item = await _self.getLastLog({envCode,projectName,index});
      let objectId = item && item._id;
      publishLogs = await _self.getLogsByPage({envCode,projectName,objectId,pageSize});
    } else {
      publishLogs = await _self.getLogsBySkip({envCode,projectName,pageNum,pageSize});
    }

    return {totalCount, publishLogs};
  },

  getLogsCount: function({envCode,projectName}) {
    return new Promise((resolve,reject)=>{
      PublishLog.getLogsCount({envCode,projectName}, function (err,data) {
        err ? reject(err) : resolve(data);
      })
    })
  },

  getLastLog: function({envCode,projectName,index}) {
    return new Promise((resolve,reject)=>{
      PublishLog.getLastLog({envCode,projectName,index}, function (err,data) {
        err ? reject(err) : resolve(data.length > 0 ? data[0]._doc : null);
      })
    })
  },

  getLogsByPage: function({envCode,projectName,objectId,pageSize}) {
    return new Promise((resolve,reject)=>{
      PublishLog.getLogsByPage({envCode,projectName,objectId,pageSize}, function (err,data) {
        err ? reject(err) : resolve(data);
      })
    })
  },

  getLogsBySkip: function({envCode,projectName,pageNum,pageSize}) {
    return new Promise((resolve,reject)=>{
      PublishLog.getLogsBySkip({envCode,projectName,pageNum,pageSize}, function (err,data) {
        err ? reject(err) : resolve(data);
      })
    })
  }
}


